// 双token认证工具类
export interface TokenPair {
  accessToken: string
  refreshToken: string
  expiresIn: number // access token过期时间（秒）
}

export interface UserInfo {
  id: string
  phone: string
  username?: string
}

class AuthManager {
  private readonly ACCESS_TOKEN_KEY = 'accessToken'
  private readonly REFRESH_TOKEN_KEY = 'refreshToken'
  private readonly TOKEN_EXPIRES_KEY = 'tokenExpires'
  private readonly USER_INFO_KEY = 'userInfo'

  // 保存token对
  setTokens(tokenPair: TokenPair): void {
    const expiresAt = Date.now() + tokenPair.expiresIn * 1000
    localStorage.setItem(this.ACCESS_TOKEN_KEY, tokenPair.accessToken)
    localStorage.setItem(this.REFRESH_TOKEN_KEY, tokenPair.refreshToken)
    localStorage.setItem(this.TOKEN_EXPIRES_KEY, expiresAt.toString())
  }

  // 获取访问令牌
  getAccessToken(): string | null {
    return localStorage.getItem(this.ACCESS_TOKEN_KEY)
  }

  // 获取刷新令牌
  getRefreshToken(): string | null {
    return localStorage.getItem(this.REFRESH_TOKEN_KEY)
  }

  // 检查访问令牌是否过期
  isAccessTokenExpired(): boolean {
    const expiresAt = localStorage.getItem(this.TOKEN_EXPIRES_KEY)
    if (!expiresAt) return true
    
    // 提前5分钟判断为过期，避免临界时间问题
    const bufferTime = 5 * 60 * 1000 // 5分钟
    return Date.now() + bufferTime >= parseInt(expiresAt)
  }

  // 检查是否已登录
  isAuthenticated(): boolean {
    const accessToken = this.getAccessToken()
    const refreshToken = this.getRefreshToken()
    return !!(accessToken && refreshToken)
  }

  // 保存用户信息
  setUserInfo(userInfo: UserInfo): void {
    localStorage.setItem(this.USER_INFO_KEY, JSON.stringify(userInfo))
  }

  // 获取用户信息
  getUserInfo(): UserInfo | null {
    const userInfoStr = localStorage.getItem(this.USER_INFO_KEY)
    if (!userInfoStr) return null
    try {
      return JSON.parse(userInfoStr)
    } catch {
      return null
    }
  }

  // 清除所有认证信息
  clearAuth(): void {
    localStorage.removeItem(this.ACCESS_TOKEN_KEY)
    localStorage.removeItem(this.REFRESH_TOKEN_KEY)
    localStorage.removeItem(this.TOKEN_EXPIRES_KEY)
    localStorage.removeItem(this.USER_INFO_KEY)
  }

  // 刷新访问令牌
  async refreshAccessToken(): Promise<boolean> {
    const refreshToken = this.getRefreshToken()
    if (!refreshToken) return false

    try {
      const response = await fetch('/api/auth/refresh', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ refreshToken })
      })

      if (!response.ok) {
        this.clearAuth()
        return false
      }

      const data = await response.json()
      this.setTokens({
        accessToken: data.accessToken,
        refreshToken: data.refreshToken,
        expiresIn: data.expiresIn
      })

      return true
    } catch (error) {
      console.error('刷新token失败:', error)
      this.clearAuth()
      return false
    }
  }

  // 获取有效的访问令牌（自动刷新）
  async getValidAccessToken(): Promise<string | null> {
    if (!this.isAuthenticated()) return null

    if (this.isAccessTokenExpired()) {
      const refreshed = await this.refreshAccessToken()
      if (!refreshed) return null
    }

    return this.getAccessToken()
  }
}

// 导出单例实例
export const authManager = new AuthManager()

// 兼容旧版本的简单方法
export const getToken = () => authManager.getAccessToken()
export const setToken = (token: string) => {
  // 为了兼容，这里设置一个默认的过期时间（1小时）
  authManager.setTokens({
    accessToken: token,
    refreshToken: token, // 临时使用相同token
    expiresIn: 3600
  })
}
export const clearToken = () => authManager.clearAuth()
export const isAuthenticated = () => authManager.isAuthenticated()
